package cn.uin.domain.auth.service.user.login.phone.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: uIn
 * @Date: 2025/10/19 - 10 - 19 - 21:59
 * @Description: 自定义认证失败返回
 * @version: 1.0
 */
@Slf4j
@Component
public class CustomPhoneAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 构建返回对象
        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("code", HttpServletResponse.SC_BAD_REQUEST);
        resultMap.put("message", exception.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(resultMap));
    }
}
